package com.qqim.client.network;

import com.qqim.common.entity.User;
import com.qqim.common.protocol.Protocol;
import com.qqim.common.utils.JsonUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.Socket;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * 客户端网络管理器
 */
public class NetworkManager {
    private static final Logger logger = LoggerFactory.getLogger(NetworkManager.class);
    
    private Socket socket;
    private BufferedReader reader;
    private PrintWriter writer;
    
    private final AtomicBoolean connected = new AtomicBoolean(false);
    private final ExecutorService executorService;
    
    private MessageListener messageListener;
    
    public NetworkManager() {
        this.executorService = Executors.newSingleThreadExecutor(r -> {
            Thread thread = new Thread(r);
            thread.setDaemon(true);
            thread.setName("NetworkManager-Reader");
            return thread;
        });
    }
    
    /**
     * 连接服务器
     */
    public boolean connect(String host, int port) {
        try {
            socket = new Socket(host, port);
            reader = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
            writer = new PrintWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF-8"), true);
            
            connected.set(true);
            
            // 启动消息接收线程
            executorService.submit(this::receiveMessages);
            
            logger.info("连接服务器成功: {}:{}", host, port);
            return true;
            
        } catch (IOException e) {
            logger.error("连接服务器失败: {}:{}", host, port, e);
            return false;
        }
    }
    
    /**
     * 断开连接
     */
    public void disconnect() {
        connected.set(false);
        
        try {
            if (reader != null) {
                reader.close();
            }
        } catch (IOException e) {
            logger.error("关闭输入流失败", e);
        }
        
        if (writer != null) {
            writer.close();
        }
        
        try {
            if (socket != null && !socket.isClosed()) {
                socket.close();
            }
        } catch (IOException e) {
            logger.error("关闭Socket失败", e);
        }
        
        logger.info("已断开服务器连接");
    }
    
    /**
     * 发送消息
     */
    public boolean sendMessage(Protocol protocol) {
        if (!connected.get() || writer == null) {
            logger.warn("未连接到服务器，无法发送消息");
            return false;
        }
        
        try {
            String message = JsonUtils.toJson(protocol);
            if (message != null) {
                writer.println(message);
                logger.debug("发送消息: {}", protocol.getType());
                return true;
            }
        } catch (Exception e) {
            logger.error("发送消息失败", e);
        }
        return false;
    }
    
    /**
     * 接收消息线程
     */
    private void receiveMessages() {
        try {
            String line;
            while (connected.get() && (line = reader.readLine()) != null) {
                handleReceivedMessage(line);
            }
        } catch (IOException e) {
            if (connected.get()) {
                logger.error("接收消息异常", e);
                // 通知连接断开
                if (messageListener != null) {
                    messageListener.onConnectionLost();
                }
            }
        } finally {
            connected.set(false);
        }
    }
    
    /**
     * 处理接收到的消息
     */
    private void handleReceivedMessage(String message) {
        try {
            logger.debug("接收到原始消息: {}", message);
            Protocol protocol = JsonUtils.fromJson(message, Protocol.class);
            if (protocol == null) {
                logger.warn("接收到无效消息: {}", message);
                return;
            }
            
            logger.debug("解析后的消息类型: {}, 发送者: {}, 数据: {}", 
                protocol.getType(), protocol.getSenderId(), protocol.getData());
            
            if (messageListener != null) {
                messageListener.onMessageReceived(protocol);
            } else {
                logger.warn("MessageListener为null，无法处理消息: {}", protocol.getType());
            }
            
        } catch (Exception e) {
            logger.error("处理接收消息失败: {}", message, e);
        }
    }
    
    /**
     * 用户登录
     */
    public boolean login(String userId, String nickname) {
        Protocol protocol = Protocol.login(userId, nickname);
        return sendMessage(protocol);
    }
    
    /**
     * 用户登出
     */
    public boolean logout(String userId) {
        Protocol protocol = Protocol.logout(userId);
        return sendMessage(protocol);
    }
    
    /**
     * 获取用户列表
     */
    public boolean getUserList() {
        Protocol protocol = Protocol.getUserList();
        return sendMessage(protocol);
    }
    
    /**
     * 发送文本消息
     */
    public boolean sendTextMessage(String senderId, String receiverId, String content) {
        Protocol protocol = Protocol.sendMessage(senderId, receiverId, content);
        return sendMessage(protocol);
    }
    
    /**
     * 发送图片
     */
    public boolean sendImage(String senderId, String receiverId, String base64Data) {
        Protocol protocol = Protocol.sendImage(senderId, receiverId, base64Data);
        return sendMessage(protocol);
    }
    
    /**
     * 发送心跳
     */
    public boolean sendHeartbeat(String userId) {
        Protocol protocol = Protocol.heartbeat(userId);
        return sendMessage(protocol);
    }
    
    /**
     * 检查连接状态
     */
    public boolean isConnected() {
        return connected.get() && socket != null && !socket.isClosed();
    }
    
    /**
     * 设置消息监听器
     */
    public void setMessageListener(MessageListener listener) {
        this.messageListener = listener;
    }
    
    /**
     * 关闭网络管理器
     */
    public void shutdown() {
        disconnect();
        if (executorService != null && !executorService.isShutdown()) {
            executorService.shutdown();
        }
    }
    
    /**
     * 消息监听接口
     */
    public interface MessageListener {
        /**
         * 接收到消息
         */
        void onMessageReceived(Protocol protocol);
        
        /**
         * 连接丢失
         */
        void onConnectionLost();
    }
} 